var Config = require('../config.js')
var md5 = require('../lib/md5.min.js')

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}


// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
})

// 显示成功提示
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
})

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: JSON.stringify(content),
        showCancel: false
    })
}

function wxPromisify(wxRequest) {
    return function(obj = {}) {
        obj.url =  obj.url.startsWith('http')? obj.url:Config.postUrl + obj.url
        if (obj.isLoading) {
            wx.showLoading({
                title: obj.loadingText || '请求中...',
            })
        }

        return new Promise((resolve, reject) => {
            obj.success = function(res) {
                resolve(res.data)
            }

            obj.fail = function(res) {
                console.log('接口请求错误', res)
                reject(res.data)
            }

            obj.complete = function(res) {
                // console.log('接口请求完成', res)
                if (obj.isLoading) {
                    wx.hideLoading()
                }
            }

            wxRequest(obj)
        })
    }
}

function getId(len, timestamp) {
    len = len || 32
    let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    let maxPos = $chars.length
    let pwd = ''
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
}

function getGlobalParam() {
    // 全局参数
    let _object = {
        id: getId(10),
        encrypt: "md5",
        sign: "",
        client: { caller: "wechat" },
        data: {},
        timestamp: new Date().getTime(),
        format: "json",
        user: wx.getStorageSync('userInfo') || {},
        userCode: 'ce5beeca-32d5-4673-be39-a001fe95e04b',
        appId: Config.appid
    }
    // md5加密
    let beforeSign = _object.id + ':' + "846d2cb0c7f09c3ae802c42169a6302b" + ":" + _object.timestamp
    let sign = md5(beforeSign)
    _object.sign = sign

    return _object
}


module.exports = {
    formatTime: formatTime,
    wxPromisify: wxPromisify,
    getId: getId,
    getGlobalParam: getGlobalParam,
    showBusy,
    showSuccess,
    showModel
}